package com.jieshuibao.service;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jieshuibao.model.db.Message;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.util.IdGen;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.push.AndroidCustomizedcast;
import com.jieshuibao.util.push.AndroidNotification;
import com.jieshuibao.util.push.IOSCustomizedcast;
import com.jieshuibao.util.push.PushType;

import net.sf.json.JSONObject;

@Component
public class PushService {
	private String appkey ="58648a2f7f2c745e2a00246a";
	private String appMasterSecret ="q4relhlb4spfvvsmmstz4mg3mmjr1qrd";
	private String appkeyIos ="5779d5e3e0f55a6e590030ad";
	private String appMasterSecretIos ="jycimsztxfhyrl3kvpsieugtz2oh51ve";
	private String timestamp = null;
	private static final Logger logger = LoggerFactory
			.getLogger("PushService.class");
	@Autowired
	private PushClientService pushClientService;
	
	@Resource
	private RedisService redisService;
	@Resource
	private MessageService messageService;
	@Resource
	private UserService userService;
	
	public void testPush(){
		JSONObject notification=new JSONObject();
		long currentTimeMillis = System.currentTimeMillis();
		timestamp=""+currentTimeMillis+"";
		notification.put("appkey", "589a7ccf310c93551f000942");
		notification.put("timestamp", timestamp);
		notification.put("type", "customizedcast");//单播  customizedcast  指定设备
		//notification.put("device_tokens", "AktFVd6CUKqT5vMj8ur_od2N-A0WnJfVz7oOH9IMlrMU");
		notification.put("alias_type", "alias");
		notification.put("alias", "ceshiji");//设备别名
		
		JSONObject payload=new JSONObject();
		
		
		payload.put("display_type", "notification");
		
		payload.put("display_type", "notification");
		
		JSONObject body=new JSONObject();
		
		
		body.put("ticker", "通知栏提示文字");
		body.put("title", "通知栏标题");
		body.put("text", "通知内容");
		body.put("after_open", "go_app");
		body.put("after_open", "go_activity");
		body.put("activity", "/question/pageList");
		
		JSONObject extra=new JSONObject();
		extra.put("sinceId", 1);
		extra.put("maxId", 10);
		
		payload.put("body", body);
		//payload.put("extra", extra);
		notification.put("payload", payload);
		/* "go_app": 打开应用
         "go_url": 跳转到URL
         "go_activity": 打开特定的activity
         "go_custom": 用户自定义内容。*/
		
		try {
			pushClientService.sendThree(notification.toString(),appMasterSecret);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	/**
	 * 
	 * @param modelType 通知模板 0 答案被采纳 1答案未采纳 2已有三条答案 3 文章被打赏4有人咨询5咨询师第一次回答
	 * @param str 参数
	 * @param alias 别名
	 * @param openAfter 0 打开应用  1 跳页面
	 * @throws Exception
	 */
	public void sendAndroidCustomizedcast(String modelType,String[] str,String alias,String openAfter) {
		try {
			AndroidCustomizedcast customizedcast = new AndroidCustomizedcast(appkey,appMasterSecret);
			//用模板控制 0 1 2 3 
			
			HashMap<String, String> map=new HashMap<String, String>();
				customizedcast.setTicker(PushType.TICKER);
				customizedcast.setTitle(PushType.TITLE_0);
				customizedcast.setTicker(PushType.TICKER);
				customizedcast.setTitle(PushType.TITLE_0);
				customizedcast.setAlias(alias, "alias");
			Message message = new Message();
			message.setMessageId(IdGen.uuid());
			map.put("messageId", message.getMessageId());
			if(modelType.equals("0")){  // 答案被采纳
				customizedcast.setText(PushType.TEXT_0_1+str[1]+PushType.TEXT_0_2+str[2]);
				map.put("type", "1");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的钱包 ");
				message.setTitle(PushType.TEXT_0_1+str[1]+PushType.TEXT_0_2+str[2]);
				message.setJumpType("1");//跳转类型
			}else if(modelType.equals("1")){ //答案未被采纳
				customizedcast.setText(PushType.TEXT_1_1+str[1]+PushType.TEXT_1_2);
				map.put("type", "1");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的钱包");
				message.setTitle(PushType.TEXT_1_1+str[1]+PushType.TEXT_1_2);
				message.setJumpType("1");//跳转类型
			}else if(modelType.equals("2")){//已收到两位咨询师的解答
				customizedcast.setText(PushType.TEXT_2_1 + str[1]);
				map.put("type", "2");//  type  1  跳到  钱包页面   2 我的提问页面  3  我的抢答页面 
				map.put("name", "我的提问");
				map.put("uuid", str[0]);//提问的uuid
				message.setJumpType("2");//跳转类型
				message.setTitle(PushType.TEXT_2_1 + str[1]);
			}else if(modelType.equals("3")){//文章被打赏
				if(StringUtils.isBlank(str[1])){
					String phone = userService.getUserByPhoneNumber(str[0]).getPhone();
					phone = phone.substring(0, 3).concat("****").concat(phone.substring(7));
					str[1] = phone;
				}
				String articleTitle = str[3];
				customizedcast.setText(PushType.TEXT_3_1+str[2]+PushType.TEXT_3_2 + articleTitle);
				map.put("type", "1");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的钱包");
				message.setTitle(PushType.TEXT_3_1+str[2]+PushType.TEXT_3_2 + articleTitle);
				message.setJumpType("1");//跳转类型
			}else if(modelType.equals("4")){//私密问（专家）
				customizedcast.setText(PushType.TEXT_4_1+str[1]+PushType.TEXT_4_2);//尊敬的咨询师，***向您发起了私密问，请及时应答。
				map.put("type", "4");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 4跳到私密问
				map.put("name", str[1]);
				map.put("uuid", str[0]);//业务id
				map.put("userId", str[2]);//userId
				message.setTitle(PushType.TEXT_4_1+str[1]+PushType.TEXT_4_2);
				message.setJumpType("4");//跳转类型
			}else if(modelType.equals("5")){//私密问（用户）
				customizedcast.setText(PushType.TEXT_5_1+str[1]+PushType.TEXT_5_2);
				map.put("type", "4");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("uuid", str[0]);//业务id
				map.put("userId", str[2]);//userId
				message.setTitle(PushType.TEXT_5_1+str[1]+PushType.TEXT_5_2);
				message.setJumpType("4");//跳转类型
			}else if(modelType.equals("6")){//关注后文章更新
				customizedcast.setText(PushType.TEXT_6_1+str[1]+PushType.TEXT_6_2 + str[2] + PushType.TEXT_6_3);
				map.put("type", "5");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "文章详情");
				map.put("uuid", str[0]);//articleId
				message.setTitle(PushType.TEXT_6_1+str[1]+PushType.TEXT_6_2 + str[2] + PushType.TEXT_6_3);
				message.setJumpType("5");//跳转类型
			}else if(modelType.equals("7")){//您咨询的问题，咨询师已给您回复
				customizedcast.setText(PushType.TEXT_7_1+str[1]);
				map.put("type", "2");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的提问");
				map.put("uuid", str[0]);//articleId
				message.setTitle(PushType.TEXT_7_1+str[1]);
				message.setJumpType("2");//跳转类型
			}else if(modelType.equals("8")){//私密问过期退款
				customizedcast.setText(PushType.TEXT_8_1);
				message.setTitle(PushType.TEXT_8_1);
			}else if(modelType.equals("9")){//快速问过期
				customizedcast.setText(PushType.TEXT_9_1);
				message.setTitle(PushType.TEXT_9_1);
			}
			if(openAfter.equals("0")){
				customizedcast.goAppAfterOpen();
			}else if(openAfter.equals("1")){
				JSONObject json = JSONObject.fromObject(map); 
				customizedcast.goCustomAfterOpen(json);
			}else {
				customizedcast.goAppAfterOpen();
			}
			/*if(map!=null){
				customizedcast.setExtraField("key", "test");
				for (Entry<String, String> entry : map.entrySet()) {  
					customizedcast.setExtraField(entry.getKey(), entry.getValue());
				}  
			}*/
			
			customizedcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
			customizedcast.setProductionMode();
			pushClientService.sendTwo(customizedcast);

			message.setUserId(alias);//用户主键
			message.setBusinessId(str[0]);//业务主键
			messageService.insertMessage(message);
		} catch (Exception e) {
			logger.warn("推送失败", e);
		}
	}
	/**
	 * 
	 * @param modelType 通知模板 0 答案被采纳 1答案未采纳 2已有三条答案 3 文章被打赏4有人咨询5咨询师第一次回答
	 * @param str 参数
	 * @param alias 别名
	 * @throws Exception
	 */
	public void sendIOSCustomizedcast(String modelType,String[] str,String alias) {
		//str[0] == 0 跳到应用 1 跳到其它页面
		try {
			IOSCustomizedcast customizedcast = new IOSCustomizedcast(appkeyIos,appMasterSecretIos);
			customizedcast.setBadge(1);
			customizedcast.setSound("default");
			customizedcast.setBadge(1);
			customizedcast.setSound("default");
			HashMap<String, String> map=new HashMap<String, String>();

			Message message = new Message();
			message.setMessageId(IdGen.uuid());
			map.put("messageId", message.getMessageId());
			if(modelType.equals("0")){// 答案被采纳
				customizedcast.setAlert(PushType.TEXT_0_1+str[1]+PushType.TEXT_0_2+str[2]);
				map.put("type", "1");//  type  1  跳到  钱包页面   2 我的提问页面  3  我的抢答页面  4 私密问
				map.put("name", "我的钱包 ");
				message.setTitle(PushType.TEXT_0_1+str[1]+PushType.TEXT_0_2+str[2]);
				message.setJumpType("1");//跳转类型
			}else if(modelType.equals("1")){//答案未被采纳
				customizedcast.setAlert(PushType.TEXT_1_1+str[1]+PushType.TEXT_1_2);
				map.put("type", "1");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", " 钱包页面  ");
				message.setTitle(PushType.TEXT_1_1+str[1]+PushType.TEXT_1_2);
				message.setJumpType("1");//跳转类型
			}else if(modelType.equals("2")){//已有三条答案   
				customizedcast.setAlert(PushType.TEXT_2_1 + str[1]);
				map.put("type", "2");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的提问  ");
				map.put("uuid", str[0]);//提问的uuid
				message.setTitle(PushType.TEXT_2_1 + str[1]);
				message.setJumpType("2");//跳转类型
			}else if(modelType.equals("3")){//文章被打赏
				map.put("type", "1");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的钱包");
				String articleTitle = str[3];
				customizedcast.setAlert(PushType.TEXT_3_1+str[2]+PushType.TEXT_3_2 + articleTitle);
				message.setTitle(PushType.TEXT_3_1+str[2]+PushType.TEXT_3_2 + articleTitle);
				message.setJumpType("1");//跳转类型
			}else if(modelType.equals("4")){//有人咨询
				customizedcast.setAlert(PushType.TEXT_4_1+str[1]+PushType.TEXT_4_2);
				map.put("type", "4");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 4跳到
				map.put("name", str[1]);
				map.put("uuid", str[0]);//业务id
				map.put("userId", str[2]);//userId
				message.setTitle(PushType.TEXT_4_1+str[1]+PushType.TEXT_4_2);
				message.setJumpType("4");//跳转类型
			}else if(modelType.equals("5")){//咨询师第一次回答
				customizedcast.setAlert(PushType.TEXT_5_1+str[1]+PushType.TEXT_5_2);
				map.put("type", "4");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", str[1]);
				map.put("uuid", str[0]);//业务id
				map.put("userId", str[2]);//userId
				message.setTitle(PushType.TEXT_5_1+str[1]+PushType.TEXT_5_2);
				message.setJumpType("4");//跳转类型
			}else if(modelType.equals("6")){//关注后文章更新
				customizedcast.setAlert(PushType.TEXT_6_1+str[1]+PushType.TEXT_6_2 + str[2] + PushType.TEXT_6_3);
				map.put("type", "5");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "文章详情");
				map.put("uuid", str[0]);//articleId
				message.setTitle(PushType.TEXT_6_1+str[1]+PushType.TEXT_6_2 + str[2] + PushType.TEXT_6_3);
				message.setJumpType("5");//跳转类型
			}else if(modelType.equals("7")){//您咨询的问题，咨询师已给您回复
				customizedcast.setAlert(PushType.TEXT_7_1+str[1]);
				map.put("type", "2");//  type  1  跳到  钱包页面   2 我的悬赏页面  3  我的抢答页面 
				map.put("name", "我的提问");
				map.put("uuid", str[0]);//articleId
				message.setTitle(PushType.TEXT_7_1+str[1]);
				message.setJumpType("2");//跳转类型
			}else if(modelType.equals("8")){//私密问过期退款
				customizedcast.setAlert(PushType.TEXT_8_1);
				message.setTitle(PushType.TEXT_8_1);
			}else if(modelType.equals("9")){//快速问过期
				customizedcast.setAlert(PushType.TEXT_9_1);
				message.setTitle(PushType.TEXT_9_1);
			}

			customizedcast.setAlias(alias, "alias");
			for (Entry<String, String> entry : map.entrySet()) {  
				customizedcast.setCustomizedField(entry.getKey(), entry.getValue());
			}  

			//使用测试模式，上线时改为生成模式
			customizedcast.setTestMode();
			//customizedcast.setProductionMode();
		
			pushClientService.sendTwo(customizedcast);


			message.setUserId(alias);//用户主键
			message.setBusinessId(str[0]);//业务主键
			messageService.insertMessage(message);
		} catch (Exception e) {
			logger.warn("推送失败", e);
		}
	}
	
	
	/**
	 * 业务推送消息（IOS和Android公用）
	 * @param modelType 通知模板： 0-答案被采纳;1-答案未采纳;2-已有两条答案 ;3-文章被打赏;4-有人咨询(私密问);5-咨询回复(私密问);
	 * 					6-关注后文章更新;7-快速问（用户）咨询师已给您回复;8-私密问过期退款;9-快速问过期退款;99-系统通知
	 * @param str {'业务主键','',''...}
	 * @param alias 被推送的用户主键
	 * @param openAfter 0 打开应用 1 跳页面
	 */
	public void pushAlias(String modelType,String[] str,String alias,String openAfter){
		Set<String> keys = redisService.keys("C_"+ alias + "*");
		if(keys!=null){
			for (String key : keys) {
				CookieUser cookieUser = redisService.getObejct(key, CookieUser.class);
				
				if(cookieUser!=null){
					int deviceType = cookieUser.getDeviceType();
					
					if(deviceType==0){
						sendIOSCustomizedcast(modelType,str,alias);
					}else{
						this.sendAndroidCustomizedcast(modelType, str, alias, openAfter);
						
						//HashMap<String,String> map = sendAndroidCustomizedcast( modelType,str,alias,openAfter);
						//logger.warn("推送信息", JsonUtil.toJson(map));
						//return map;
					}
				}
				
			}
		}
	}
}
